/**
 * Copyright 2009 Wisdom 
 */
package com.wisdom.model.dao.hibernate;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.wisdom.exceptions.UserNotFoundException;
import com.wisdom.model.dao.UserDao;
import com.wisdom.model.entities.User;

/**
 * Hibernate implements for user data access object
 * 
 * @author alekseiko
 * @since 1.0
 */
@Transactional
@Repository("userDao")
public class HibernateUserDao implements UserDao {

    @Resource
    private HibernateTemplate template;
    
    /**
     * {@inheritDoc}
     * @throws UserNotFoundException 
     */
    public User getUser(String login) throws UserNotFoundException {
    	DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
    	criteria.add(Expression.eq("login", login));
    	
    	List<User> ans = template.findByCriteria(criteria);
    	
    	System.out.println(ans.size());
    	
    	User ret;
    	if (ans.size() == 0)
    		throw new UserNotFoundException();
    	else
    		ret = ans.get(0);
    	
    	ret.setEnterDate(new Date());
    	template.update(ret);
    	
    	return ret;
    }

	public void addUser(User user) {
		template.save(user);
	}

	public boolean checkPassword(String pass) {
		if (pass.length() > 6)
			return true;
		else
			return false;
	}

	public void deleteUser(User user) {
		template.delete(user);
	}

	public boolean isCorrectLogin(String login) {
		DetachedCriteria cr = DetachedCriteria.forClass(User.class);
		cr.add(Expression.eq("login", login));
		List<User> ans = template.findByCriteria(cr);
		if (ans.size() == 0)
			return true;
		return false;
	}

	public void updateUser(User user) {
		template.update(user);
		
	}
	
	public List<User> listUsers(){
		return template.find("from User user");
	}

	public User deleteUser(String login) throws UserNotFoundException {
		User user = getUser(login);
		deleteUser(user);	
		return user;
	}

}
